#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
@Author : JoeyGosson
@Time   : 2019/10/08 14:40
@File   : log_model.py
'''
import logging.handlers, logging, os


def create_logger(dty="logs", log_name="{}.log", max_part=5, max_size=50, isPrint=False, file_name="models", level=logging.DEBUG):
    '''
    :param dty: 日志保存文件夹(没有则自动创建)
    :param log_name: 日志保存文件名(没有则自动创建)
    :param max_aprt: 最多保存几份日志文件(默认5份,最大20份)
    :param max_size: 每份日志保存的大小(默认10m, 最大200m)
    :param isPrint: 是否打印控制台(默认不打印:False)
    :param level: 日志等级(默认Debug)
    :return: 日志实例对象
    '''
    if max_part >= 10:
        max_part = 10
    if max_part < 5:
        max_part = 5
    if max_size >= 100:
        max_size = 100
    if max_size < 10:
        max_size = 10

    logger_name = "example_{}".format(file_name)
    logger = logging.getLogger(logger_name)
    if not logger.handlers:
        logger.setLevel(level)

        if not os.path.isdir(dty):
            os.mkdir(dty)
        logfile_name = os.path.join(dty, log_name.format(file_name))
        fh = logging.handlers.RotatingFileHandler(logfile_name, maxBytes=max_size * 1000 * 1000, backupCount=max_part)
        fh.setLevel(logging.DEBUG)

        if isPrint:
            ch = logging.StreamHandler()
            ch.setLevel(logging.DEBUG)

        datefmt = "%a %d %b %Y %H:%M:%S"
        formatter = logging.Formatter(
            "%(asctime)s %(levelname)s %(filename)s %(lineno)d %(thread)d %(process)d %(message)s", datefmt)
        fh.setFormatter(formatter)
        logger.addHandler(fh)

        if isPrint:
            ch.setFormatter(formatter)
            logger.addHandler(ch)

    return logger
